package com.bjpowernode.springsecurity01.filter;


import com.bjpowernode.springsecurity01.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class CaptchaCodeFilter extends OncePerRequestFilter {

    @Resource
    private ObjectMapper objectMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String requestURL = request.getRequestURI();

        if (requestURL.equals("/login/doLogin")){

            String sessionCode = (String) request.getSession().getAttribute("code");

            String code = request.getParameter("code");

            if(!sessionCode.equalsIgnoreCase(code)){
                Result result = new Result(-1,"验证码不一致");

                String jsonStr = objectMapper.writeValueAsString(result);

                response.getWriter().write(jsonStr);

                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
